package com.udg.goodmorning.tweet;

import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import twitter4j.ResponseList;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.http.AccessToken;
import twitter4j.http.OAuthAuthorization;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

/**
 * キーワード監視処理<br>
 * タイムラインを監視し、キーワードがあればアラームを鳴らす。
 * @author Ippei Shimobou
 *
 */
public class TWakeCallMain extends Service {

	// 使用していないためコメントアウト by Shimobou
	//private TextView textView;
	//private CommonsHttpOAuthConsumer consumer;
	//private OAuthProvider provider;
	//private static String newText = "";

	private String regex = "ping";	// Target Tweet
	private Pattern mPattern;
	public static KeyguardManager.KeyguardLock klock;

	@Override
	public void onCreate() {
		super.onCreate();
		(new Thread(runnable)).start();
	}

	private Runnable runnable = new Runnable() {
		/**
		 * スレッド実行関数<br>
		 * タイムラインを取得し、サービスを停止する。
		 */
		@Override
		public void run() {
			getTimeline();
			stopSelf();
		}
	};

	/**
	 * タイムラインの取得
	 */
	private void getTimeline() {
		if(Utility.DEBUG)Log.d("GMT", "TWakeCallMain::getTimeline -Start-");
		Twitter mTwitter = new TwitterFactory().getInstance();
		Configuration config = new ConfigurationBuilder().build();

		SharedPreferences pref = getSharedPreferences("token", MODE_PRIVATE);
		String oauthToken = pref.getString("token", "");
		String oauthTokenSecret = pref.getString("tokenSecret", "");

		SharedPreferences OnOffPref = getSharedPreferences("on_off_time",
				MODE_PRIVATE);
		SharedPreferences.Editor editor = OnOffPref.edit();
		String endTime = OnOffPref.getString("on_time", "");

		try {

			// CONSUMER KEYとCONSUMER SECRET、
			// access_tokenとaccess_token_secretを使って、
			// twitterインスタンスを取得する。
			Twitter twitter = new TwitterFactory(config)
					.getInstance(new OAuthAuthorization(config,
							Utility.consumerKey, Utility.consumerSecret,
							new AccessToken(oauthToken, oauthTokenSecret)));

			// 任意の文字列を引数にして、ツイート。
			// twitter.updateStatus("てすとしてますーごめんなさい。");

			// Mention Get
			ResponseList<twitter4j.Status> statuses = null;
			statuses = twitter.getMentions();


			int len = statuses.size();
			if(len == 0){
				return;
			}

			/* initalize for Loop */
			int cnt = 0;
			twitter4j.Status status = statuses.get(cnt);
			Boolean retParse = false;

			while (true) {

				if(Utility.DEBUG)Log.v("TWakecall-Parsing","While Top");

				/*
				 * When is this loop end?
				 *  1. The time getting from Preference which is named
				 *         "on_off_prefs" < Newest Mention time
				 *  2. len > cnt
				 *  3. The data that return from parse() is true
				 */
				if (Long.parseLong(endTime) >= status.getCreatedAt().getTime()) {
					if(Utility.DEBUG){
						Log.v("DEBUG----","--------------------1----------------------");
						Log.v("TWakecall-Parsing","Break here@ endTime["+endTime+"]getTime["+status.getCreatedAt().getTime());
					}
					editor.putString("on_time",
							Long.toString(System.currentTimeMillis()));
					editor.commit();
					break;
				}
				if (retParse | cnt >= len) {
					if(Utility.DEBUG)Log.v("DEBUG----","--------------------2----------------------");
					editor.putString("on_time",
							Long.toString(System.currentTimeMillis()));
					editor.commit();
					break;
				}

				/* count up */
				retParse = parse(status);
				status = statuses.get(++cnt);
			}
		} catch (TwitterException e) {
			Log.e("GMT", e.toString());
		}
		if(Utility.DEBUG)Log.d("GMT", "TWakeCallMain::getTimeline -Start-");
	}

	private String Date2String(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int y = cal.get(Calendar.YEAR);
		int m = cal.get(Calendar.MONTH);
		int d = cal.get(Calendar.DAY_OF_MONTH);
		int h = cal.get(Calendar.HOUR_OF_DAY);
		int min = cal.get(Calendar.MINUTE);
		int sec = cal.get(Calendar.SECOND);

		String ret = y + "/" + m + "/" + d + " " + min + ":" + sec;
		return ret;
	}

	/**
	 * キーワード判定を行う。<br>
	 * パースというメソッド名だがキーワード判定とMorningCall呼び出しまで行う。
	 *
	 * @param status
	 * @return TRUE:キーワード有り FALSE:キーワード無し
	 */
	private boolean parse(twitter4j.Status status) {
		mPattern = Pattern.compile(regex);
		Matcher mMatcher = mPattern.matcher(status.getText());
		String mentionFrom = "@" + status.getUser().getScreenName();
		String message = status.getText();
		if(Utility.DEBUG)
			Log.v("DEBUG----","Now Parsing Message is ["+message+"]");

		/* Filter */
		// if(status.getUser().getScreenName().equals("kobashinG")){
		/* KeyWords */
		if (mMatcher.find()) {
			if(Utility.DEBUG)Log.d("GMT", "TWakeCallMain::parse find keyword!");
			/* Wake状態へ移行 */
			PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
			PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
			        | PowerManager.ACQUIRE_CAUSES_WAKEUP
			        | PowerManager.ON_AFTER_RELEASE, "GoodMorningTweet");
			wakelock.acquire();
			wakelock.release();
			
			/* KeyGuardを解除 */
			KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
			klock = km.newKeyguardLock("Your App Tag");
			klock.disableKeyguard();
			
			/* Sound Play */
			Intent wakeUpIntent = new Intent(this, MorningCall.class);
			wakeUpIntent.putExtra("text_title", mentionFrom);
			wakeUpIntent.putExtra("text_Message", message);
			wakeUpIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_NO_USER_ACTION);

			this.startActivity(wakeUpIntent);
			return true;
		}
		// }
		return false;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}